import Axios from 'axios'
import { getCache } from '@/utils/cache'
import { showNotify } from 'vant'
import { useUserStore } from '@/stores/user'

declare module 'axios' {
  interface AxiosRequestConfig {
    showError?: boolean
  }
}

const request = Axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
  showError: true
})

// 请求拦截器
request.interceptors.request.use((config) => {
  const token = getCache('token')
  if (token) {
    config.headers.batoken = token
  }
  const virtualToken = getCache('virtualToken')
  if (virtualToken) {
    config.headers.virtualToken = virtualToken
  }
  config.headers.app = 'H5'
  return config
})

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.config.url == '/api/Uniform/xcode') {
      console.log(response.data)
      return response.data
    }
    const { code, data } = response.data
    if (code === 1) {
      return data
    } else if (code === 303) {
      const { logout } = useUserStore()
      logout()
      window.location.href = '/login'
    } else if (code === 204 || code === 201) {
      console.log(code)
      return Promise.reject(response.data)
    }
    if (response.config.showError) {
      showNotify({
        type: 'danger',
        message: response.data.msg
      })
    }
    throw new Error(response.data.msg)
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default request
